
# 私人律师
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from service.models import PrivateContract, PersonInfo, CompanyContract, CompanyInfo, CompanyPerson
from wxchat.models import WxUserInfo


@receiver(post_save, sender=PrivateContract)
def update_persion_info(sender, instance, created, **kwargs):

    if instance.openid:
        user_info = {
            'name': instance.name,
            'telephone': instance.telephone,
            'id_card': instance.id_card,
        }
        obj, created = PersonInfo.objects.update_or_create(defaults=user_info, openid=instance.openid)
        print(obj, created)


@receiver(post_save, sender=CompanyContract)
def update_wxuser_info(sender, instance, created, **kwargs):

    if created:
        return
    if instance.is_confirm:
        user = WxUserInfo.objects.filter(openid=instance.openid).first()
        if user:
            user.member_role_id = 5     # 商户
            user.save()
    else:
        WxUserInfo.objects.filter(openid=instance.openid).update(member_role_id=None)


@receiver(post_save, sender=CompanyInfo)
def update_company_person(sender, instance, created, **kwargs):
    if instance.is_agency == 1 and instance.contact_person is not None:
        person_info = {
            'name': instance.contact_person,
            'telephone': instance.contact_tel,
            'company_id': instance.id
        }
        obj, created = CompanyPerson.objects.update_or_create(defaults=person_info, openid=instance.openid)
        WxUserInfo.objects.filter(openid=instance.openid).update(name=instance.contact_person, telephone=instance.contact_tel)
        print(obj, created)


@receiver(post_save, sender=CompanyPerson)
def update_user_info(sender, instance, created, **kwargs):

    user = WxUserInfo.objects.filter(openid=instance.openid).first()
    if user and user.member_role_id != 2:
        user.member_role_id = 2
        user.save()


@receiver(post_delete, sender=CompanyPerson)
def update_user_role(sender, instance, **kwargs):

    user = WxUserInfo.objects.filter(openid=instance.openid).first()
    if user:
        user.member_role_id = None
        user.save()
